package org.jeecg.modules.qyxxora.controller;

import java.lang.reflect.Field;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.modules.redisson.client.RedissonLockClient;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.annotations.OrgPermissionAnnotation;
import org.jeecg.config.util.CurrentOrgInfoUtil;
import org.jeecg.modules.qyxxora.entity.ResetIndexLog;
import org.jeecg.modules.qyxxora.entity.ZbjkScyszbjcMx;
import org.jeecg.modules.qyxxora.entity.dto.ScyszbjcMxBatchCheckDto;
import org.jeecg.modules.qyxxora.service.IResetIndexLogService;
import org.jeecg.modules.qyxxora.service.IZbjkScyszbjcMxService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;

import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 生产要素指标监测明细
 * @Author: jeecg-boot
 * @Date: 2021-12-23
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "生产要素指标监测明细")
@RestController
@RequestMapping("/qyxx/zbjkScyszbjcMx")
public class ZbjkScyszbjcMxController extends JeecgController<ZbjkScyszbjcMx, IZbjkScyszbjcMxService> {
    @Autowired
    private IZbjkScyszbjcMxService zbjkScyszbjcMxService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IResetIndexLogService resetIndexLogService;

    /**
     * 分页列表查询
     *
     * @param zbjkScyszbjcMx
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-分页列表查询")
    @ApiOperation(value = "生产要素指标监测明细-分页列表查询", notes = "生产要素指标监测明细-分页列表查询")
    @GetMapping(value = "/list")
    @OrgPermissionAnnotation
    public Result<?> queryPageList(ZbjkScyszbjcMx zbjkScyszbjcMx,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        zbjkScyszbjcMx.setDjxh(CurrentOrgInfoUtil.getCurrentOrgShxydm());
        QueryWrapper<ZbjkScyszbjcMx> queryWrapper = QueryGenerator.initQueryWrapper(zbjkScyszbjcMx, req.getParameterMap());
        Page<ZbjkScyszbjcMx> page = new Page<ZbjkScyszbjcMx>(pageNo, pageSize);
        IPage<ZbjkScyszbjcMx> pageList = zbjkScyszbjcMxService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param zbjkScyszbjcMx
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-添加")
    @ApiOperation(value = "生产要素指标监测明细-添加", notes = "生产要素指标监测明细-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ZbjkScyszbjcMx zbjkScyszbjcMx) {
        zbjkScyszbjcMxService.save(zbjkScyszbjcMx);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param zbjkScyszbjcMx
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-编辑")
    @ApiOperation(value = "生产要素指标监测明细-编辑", notes = "生产要素指标监测明细-编辑")
    @PutMapping(value = "/edit")
    @RequiresPermissions("scysjcjg:check")
    public Result<?> edit(@RequestBody ZbjkScyszbjcMx zbjkScyszbjcMx) {
        ZbjkScyszbjcMx scyszbjcMxOld = zbjkScyszbjcMxService.getById(zbjkScyszbjcMx.getId());
        //2表示已核查, 已核查的不能修改
        if (scyszbjcMxOld.getClzt() != null && scyszbjcMxOld.getClzt() == 2) {
            return Result.error("当前记录已核查，不能修改");
        }
        zbjkScyszbjcMxService.updateById(zbjkScyszbjcMx);
        return Result.OK("编辑成功!");
    }

    /**
     * 生产要素指标监测明细-批量处理
     *
     * @param dto
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-批量处理")
    @ApiOperation(value = "生产要素指标监测明细-批量处理", notes = "生产要素指标监测明细-批量处理")
    @PostMapping(value = "/batchCheck")
    public Result<?> batchCheck(@RequestBody ScyszbjcMxBatchCheckDto dto) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //先遍历记录判断是否都已经查询
        List<String> idList = dto.getIdList();
        List<ZbjkScyszbjcMx> scyszbjcMxList = new ArrayList<>();
        for (String id : idList) {
            ZbjkScyszbjcMx scyszbjcMx = new ZbjkScyszbjcMx();
            ZbjkScyszbjcMx scyszbjcMxOld = zbjkScyszbjcMxService.getById(id);
            if (scyszbjcMxOld.getClzt() != null && scyszbjcMxOld.getClzt() == 2) {
                return Result.error("【" + scyszbjcMxOld.getZbmc() + "】记录已核查，不能重复处理");
            }
            scyszbjcMx.setId(id);
            scyszbjcMx.setClzt(2);
            scyszbjcMx.setCljg(dto.getCljg());
            scyszbjcMx.setCljgsm(dto.getCljgsm());
            //设置处理人信息
            scyszbjcMx.setClr(loginUser.getId());
            scyszbjcMx.setClrLxdh(loginUser.getPhone());
            scyszbjcMx.setClrXm(loginUser.getRealname());
            scyszbjcMx.setClsj(new Date());
            scyszbjcMxList.add(scyszbjcMx);
        }
        zbjkScyszbjcMxService.updateBatchById(scyszbjcMxList);
        return Result.OK("处理成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-通过id删除")
    @ApiOperation(value = "生产要素指标监测明细-通过id删除", notes = "生产要素指标监测明细-通过id删除")
//	@DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        zbjkScyszbjcMxService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-批量删除")
    @ApiOperation(value = "生产要素指标监测明细-批量删除", notes = "生产要素指标监测明细-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.zbjkScyszbjcMxService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "生产要素指标监测明细-通过id查询")
    @ApiOperation(value = "生产要素指标监测明细-通过id查询", notes = "生产要素指标监测明细-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ZbjkScyszbjcMx zbjkScyszbjcMx = zbjkScyszbjcMxService.getById(id);
        return Result.OK(zbjkScyszbjcMx);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param zbjkScyszbjcMx
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZbjkScyszbjcMx zbjkScyszbjcMx) {
        if (StringUtils.isBlank(zbjkScyszbjcMx.getDjxh())) {
            throw new JeecgBootException("企业ID不能为空");
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //Set<String> roleNameListString = sysUserService.getUserRolesSet(loginUser.getUsername());
        //if (roleNameListString.contains("superAdmin") || roleNameListString.contains("sysProvinceAdmin") || roleNameListString.contains("provinceAdmin")) {
        if (SecurityUtils.getSubject().isPermitted("earlyResult:list:fzsxAndFzxx")) {
            return super.exportXls(request, zbjkScyszbjcMx, ZbjkScyszbjcMx.class, "生产要素指标监测明细");
        }
        return super.exportXls(request, zbjkScyszbjcMx, ZbjkScyszbjcMx.class, "生产要素指标监测明细", getFieldsNoFz());
    }

    private String getFieldsNoFz() {
        //实体类中字段与未授权字段比较，列出需导出字段
        Field[] fileds = ZbjkScyszbjcMx.class.getDeclaredFields();
        List<Field> list = new ArrayList(Arrays.asList(fileds));
        List<String> exportList = new ArrayList<>();
        list.forEach(e -> {
            if (e.isAnnotationPresent(Excel.class) && !e.getName().equals("fzSx") && !e.getName().equals("fzXx")) {
                exportList.add(e.getName());
            }
        });
        return String.join(",", exportList);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZbjkScyszbjcMx.class);
    }


    //添加调用存储过程重新加工接口。
    @AutoLog(value = "调用存储过程重新加工接口")
    @ApiOperation(value = "调用存储过程重新加工接口", notes = "调用存储过程重新加工接口")
    @RequiresPermissions("targetManagement:rerun:btn")
    @RequestMapping(value = "/resetIndexProcess", method = RequestMethod.GET)
    public Result<?> resetIndexProcess(@RequestParam String ssrq) {
        boolean flag = zbjkScyszbjcMxService.resetIndexProcess(ssrq);
        if (flag) {
            return Result.OK();
        } else {
            return Result.error("调度重跑指标任务异常");
        }
    }


    @AutoLog(value = "查询重跑指标调度日志")
    @ApiOperation(value = "查询重跑指标调度日志", notes = "查询重跑指标调度日志")
    @RequestMapping(value = "/selectIndexProcessLog", method = RequestMethod.GET)
    public Result<Page<ResetIndexLog>> selectIndexProcessLog(@RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<ResetIndexLog> list = resetIndexLogService.selectIndexProcessLog(currentPage,pageSize);
        return Result.OK(list);
    }
}
